# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : mapReduce聚合操作3.py
# @Author: dongguangwen
# @Date  : 2025-06-15 17:08
# pip install pymongo==3.12.3  4.0+版本不支持
from pymongo import MongoClient

client = MongoClient('mongodb://root:root123@192.168.1.119:27017/')
db = client['learning_mongodb']
collection = db['users']


# 添加查询条件：只统计活跃用户
query = {"is_active": True}

# Mapper
mapper = """
function () {
    emit(this.address.city, 1);
}
"""

# Reducer
reducer = """
function (key, values) {
    return Array.sum(values);
}
"""

# 执行带过滤的 MapReduce
result = collection.map_reduce(
    mapper,
    reducer,
    out="active_city_users",
    query=query
)

# 输出结果
print("活跃用户的城市分布：")
for doc in result.find():
    print(f"{doc['_id']}: {doc['value']}")

"""
活跃用户的城市分布：
Guangzhou: 1.0
Shenzhen: 2.0
Beijing: 1.0
"""